// Copyright (C), 2012-2018, Sichuan Xiaoka Technology Co., Ltd.
package crypto;


import constant.Constants;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * Base64编码工具
 *
 * @author 肖波
 * @since 1.0
 */
public class Base64Utils {

    /**
     * <p>
     * BASE64字符串解码为二进制数据
     * </p>
     *
     * @param base64 base64
     * @return 源二进制数据
     * @throws
     */
    public static byte[] decode(String base64) {
        try {
            return Base64.getDecoder().decode(base64.getBytes(Constants.UTF_8));
        } catch (UnsupportedEncodingException e) {
            throw new CryptoException(e.getMessage());
        }
    }

    /**
     * <p>
     * 二进制数据编码为BASE64字符串
     * </p>
     *
     * @param bytes base64
     * @return BASE64后的二进制数据
     * @throws
     */
    public static String encode(byte[] bytes) {
        try {
            return new String(Base64.getEncoder().encode(bytes), Constants.UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new CryptoException(e.getMessage());
        }
    }

    public static String encodeToString(byte[] toByteArray) {
        return new String(toByteArray);
    }
}